RefreshAuthInterceptor   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 22
dl 0
loc 39
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A isTokenExpired 0 10 1
A errorHandler 0 22 4
1
import ResponseInterceptor from './response-interceptor'
2
import { AxiosResponse } from 'axios';
3
4
/**
5
 * If access token is not valid try to renew authentication
6
 * and retry the previous call.
7
 */
8
export default class RefreshAuthInterceptor extends ResponseInterceptor {
9
10
    /**
11
     * If the error is 401 for token expired try to renew tokens re-send the original request.
12
     *
13
     * @param error The original error.
14
     */
15
    public async errorHandler(error: any): Promise<any> {
16
        if (!error.response || !this.isTokenExpired(error.response)) {
17
            // Not an expired token's fault.
18
            if (error.response?.status === 401) { // if 401 clear tokens
19
                const storage = this.beditaClient.getStorageService();
20
                await storage.clearTokens();
21
                await storage.remove('user');
22
            }
23
24
            return Promise.reject(error);
25
        }
26
27
        await this.beditaClient.renewTokens();
28
        delete error.config.headers.Authorization;
29
30
        return await this.beditaClient.request(error.config);
31
    }
32
33
    /**
34
     * Return `true` if it's a token expired response error.
35
     *
36
     * @param response The response
37
     */
38
    protected isTokenExpired(response: AxiosResponse): boolean {
39
        const code = response.data && response.data.error && response.data.error.code;
40
41
        return response.status === 401 && code === 'be_token_expired';
42
    }
43
}
44